const express = require('express')
const router = express.Router()
const nodemailer = require("nodemailer")
const userDB = require('../../db/user')
const codeDB = require('../../db/regcode')

// 用户注册
router.post('/', async (req, res) => {  
  let {user, pass, email, code} = req.body
  let userReg = /^[^\s]{2,8}$/,
      passReg = /^[\w,.?;<>/|\\:'"!@#$%^&*()+-]{6,16}$/,
      emailReg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/

  if(!userReg.test(user)){
    return res.send({
      code: 1,
      msg: '用户名格式为2-8位非空格字符'
    })
  }
  if(!passReg.test(pass)){
    return res.send({
      code: 1,
      msg: '密码格式为6-16位字符'
    })
  }
  if(!emailReg.test(email)){
    return res.send({
      code: 1,
      msg: '邮箱格式错误'
    })
  }
  if(!code){
    return res.send({
      code: 1,
      msg: '验证码不能为空'
    })
  }

  let doc
  doc = await userDB.findOne({user})
  if(doc){
    return res.send({
      code: 2,
      msg: '该用户名已注册'
    })
  }
  doc = await userDB.findOne({email})
  if(doc){
    return res.send({
      code: 2,
      msg: '该邮箱已注册'
    })
  }
  

  let codeDoc = await codeDB.findOne({email})
  let codeTime = Date.now() - codeDoc.date
  let tenMinutes = 10 * 60 * 1000
  // 验证码10分钟有效期
  if(codeTime > tenMinutes){
    return res.send({
      code: 4,
      msg: '验证码已过期'
    })
  }

  if(codeDoc.code !== +code){
    return res.send({
      code: 3,
      msg: '验证码不正确'
    })
  }

  let userDoc = await userDB.create({user, email, pass})

  res.send({
    code: 0,
    msg: '用户注册成功'
  })

  let transporter = nodemailer.createTransport({
    host: "smtp.qq.com", // 发送方邮箱
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
      user: 'charlesxtd@foxmail.com', // 发送方邮箱地址
      pass: 'sxmbbzfhmxujbgif' // 授权码 这个有了才可以发送邮件，在163邮箱中看
    }
  })

  let formatDate = (val) => {
    let date = new Date(val),
      YY = date.getFullYear(),
      MM = date.getMonth() + 1,
      DD = date.getDate(),
      hh = date.getHours(),
      mm = date.getMinutes(),
      ss = date.getSeconds()
  
    hh < 10 && (hh = '0' + hh)
    mm < 10 && (mm = '0' + mm)
    ss < 10 && (ss = '0' + ss)
  
    return `${YY}-${MM}-${DD} ${hh}:${mm}:${ss}`
  }

  let option = {
    from: 'charlesxtd@foxmail.com', // sender address
    to: email, // list of receivers
    subject: "博客[無夢]注册信息", // Subject line
    html: `<div style="background-color:#eef2fa;border:1px solid #d8e3e8;color: #111;padding:0 15px;-moz-border-radius:5px;-webkit-border-radius:5px;-khtml-border-radius:5px;">
           <p style="font-weight: bold;color: #2196F3;font-size: 18px;">注册信息</p>
           <p>您好，<a href="mailto:${email}" rel="noopener" target="_blank">${email}</a></p>
           <p>内容: 注册成功！ 用户名: ${user}</p>
           <p>时间: ${formatDate(userDoc.regDate)}</p>
           <p>博客：<a href="http://www.lessmore.cc" target="_blank">無夢</a></p>
           </div>`
  }
  
  // 发送邮件
  transporter.sendMail(option, (err, data) => {
    if (err) {
      // console.log(err)
      res.send({
        code: err.responseCode,
        msg: err.response
      })
    } else {
      res.send({
        code: 0,
        msg: '邮件发送成功',
        data
      })
    }
  })
})



module.exports = router